#include <iostream>
#include <unistd.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <pthread.h>

int tiketes = 1000;

class Tiketes
{
private:
    int tiketes;
    pthread_mutex_t mtx;

public:
    Tiketes()
        : tiketes(1000)
    {
        pthread_mutex_init(&mtx, NULL);
    }
    ~Tiketes()
    {
        pthread_mutex_destroy(&mtx);
    }

    bool gettiketes()
    {
        bool flag=true;
        pthread_mutex_lock(&mtx);
        if (tiketes > 0)
        {
            usleep(1000);
            std::cout << "我是[" << pthread_self() << "] 我要抢的票是： " << tiketes << std::endl;
            --tiketes;
            printf(" ");
        }
        else
        {
          std::cout<<"票抢完了"<<std::endl;
          flag=false;
        }
          pthread_mutex_unlock(&mtx);
          return flag;
    }
};

void *threadrun(void *args)
{
     Tiketes* tk=  (Tiketes*)args; 
    
    while(1)
    {
       if(!tk->gettiketes())
       break;
    }
}

int main()
{
    Tiketes* tk=new Tiketes();

    pthread_t tid[5];
    for (int i = 0; i < 5; ++i)
    {
        pthread_create(tid + i, NULL, threadrun, (void*)tk);
    }
    for (int i = 0; i < 5; ++i)
    {
        pthread_join(tid[i], NULL);
    }

    return 0;
}
